package cn.itcast.chapter04.response;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class PrintServlet
 */
public class PrintServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * 1、响应行相关的方法，就是设置状态码以及错误信息
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    // 1、响应行相关的方法，就是设置状态码以及错误信息
	    // rowMethod(response);
	    headerMethod(response);
	    // byteStreamMethod(response);
	    // charStreamMethod(response);
	    
	}

    private void charStreamMethod(HttpServletResponse response) throws IOException {
        // 3.2、使用字符流向浏览器输出数据
	    // 首先获取字符流
	    PrintWriter out = response.getWriter();
	    String value = "HelloWorld....................";
	    out.write(value);
    }

    private void byteStreamMethod(HttpServletResponse response) throws IOException {
        // 3、响应体相关方法
	    // 3.1、字节流对象，向浏览器返回数据
	    ServletOutputStream out = response.getOutputStream();
	    String value = "HelloWorld!!!";
	    out.write(value.getBytes());
    }

    private void headerMethod(HttpServletResponse response) {
        // 2、与响应头相关的方法(响应消息头通常跟状态码配合使用才会出现效果)
	    // 在用户名和密码输入错误的情况下，重新回到登录页面，让用户重新输入用户名和密码
	    // 2.1、设置状态码
	    response.setStatus(302);
	    // 2.2、设置响应头，完成重定向到登录页面
	    response.setHeader("Location", "/web_03/login.html");
	    System.out.println("设置成功!!!");
    }

    private void rowMethod(HttpServletResponse response) throws IOException {
        response.sendError(404, "web_03项目的请求资源不存在!!!!!!ahhhh");
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
